import classnames from 'classnames'
import { useEffect, useRef, useState } from 'react'
import Icon from '../Icon'
import styles from './index.module.scss'

/**
 * 拥有懒加载特性的图片组件
 * @param {String} props.src 图片地址
 * @param {String} props.className 样式类
 */
type Props = {
  src: string
  className?: string
  alt:string
}
const Image = ({ src, className }: Props) => {
  // 对图片元素的引用
  const imgRef = useRef<HTMLImageElement>(null)
  // 判断图片是否正在加载
  const [onLoad, setOnLoad] = useState(true)
  // 判断图片是否出错
  const [error, setError] = useState(true)
  useEffect(() => {
    const or = new IntersectionObserver(entries => {
      if (entries[0].isIntersecting) {
        imgRef.current!.src = imgRef.current?.getAttribute('data-src')!
      }
    }, { rootMargin: '100px' })
    or.observe(imgRef.current!)
  }, [])

  return (
    <div className={classnames(styles.root, className)}>
      {/* 正在加载时显示的内容 */}
      {
        onLoad && <div className="image-icon">
          <Icon type="iconphoto" />
        </div>
      }

      {/* 加载出错时显示的内容 */}
      {
       !error && <div className="image-icon">
          <Icon type="iconphoto-fail" />
        </div>
      }

      {/* 加载成功时显示的内容 */}
      {<img onLoad={() => { setOnLoad(false) }} onError={() => { setError(false) }} alt="" data-src={src} ref={imgRef} />}
    </div>
  )
}

export default Image
